const express = require('express')

const app = express() // express实例对象

// 用户列表
const userList = [{ username: 'admin', password: 123456 }]

// http://ip:port/user
// 创建一个名为/user的路由
// request请求对象，
// response 响应对象
app.get('/user', (request, response) => {
	console.log('request >>>>>')
	response.send('hello world') // 响应内容
})

// http://ip:port/login?username=admin&password=123

// 获取get请求的参数，使用request.query
app.get('/login', (request, response) => {
	// 接收参数
	const username = request.query.username //用户名
	const password = request.query.password //密码
	console.log('username :', username, '  password :', password)

	const user = userList.find(item => item.username == username && item.password == password)

	if (user) {
		response.send({
			code: 1,
			message: '登录成功',
			user: {
				username,
				password,
			},
		})
	} else {
		response.send({
			code: -1,
			message: '登录失败,用户名或密码出错！',
		})
	}
})

/**
 * 注册
 *   http://ip:port/register?username=root&password=123
 */
app.get('/register', (request, response) => {
	//1. 获取注册用户名和密码
	const username = request.query.username
	const password = request.query.password

	//2.保存注册用户信息
	userList.push({
		username,
		password,
	})

	response.send({
		code: 1,
		message: '注册成功!',
	})
})

// 启动web程序
app.listen(3000, () => console.log('监听3000端口,启动程序...'))
